<template>
  <el-dialog
    :title="type==='build'?'创建群聊':'邀请成员'"
    :visible.sync="isshow"
    width="800px"
    @close="concleBuild"
  >
    <div class="buildContent">
      <div class="content_l">
        <div class="search_bar">
          <el-input
            placeholder="请输入内容"
            prefix-icon="el-icon-search"
            v-model="search_user"
            clearable
          >
          </el-input>
        </div>
        <div class="groupList">
          <el-tree
            :data="userList"
            :props="defaultProps"
            node-key="id"
            ref="tree"
            show-checkbox
            :filter-node-method="filterNode"
            @check="getCheckedKeys"
          >
            <div slot-scope="{ data}" class="custom_tree_node">
              <div class="user_avatar" v-if="data.level!=1">
                <img :src="data.avatar||require('@/assets/images/head_img.png')" alt="加载失败">
              </div>
              <div>
                <div :class="data.level==1?'branch_name':'user_name'">{{ data.label }}</div>
              </div>
            </div>
          </el-tree>
        </div>
      </div>
      <div class="content_r">
        <div class="checks_title">
          <div>选择成员</div>
          <div>已选择{{ filterSelectedData.length }}名成员</div>
        </div>
        <div class="checkUser" v-if="filterSelectedData.length!=0">
          <div v-for="(item,index) in filterSelectedData" :key="item.id" class="checkuserItem">
            <div class="item_avatar">
              <img :src="item.avatar||require('@/assets/images/head_img.png')"/>
              <div>{{ item.label }}</div>
            </div>
            <div class="delCheck" @click="delCheck(item,index)">
              <i class="el-icon-circle-close"></i>
            </div>
          </div>
        </div>

      </div>
    </div>

    <span slot="footer" class="dialog-footer">
      <el-button @click="concleBuild">取消</el-button>
      <el-button type="primary" @click="confirmBuild" :disabled="filterSelectedData.length===0"
      >{{ type == 'build' ? '确认创建' : '确认邀请' }}</el-button>
  </span>
  </el-dialog>
</template>

<script>
import { getuserTree } from '@/api/library/librarySet'
import { createGroup, groupUserTree, inviteUser } from '@/api/library_groupList/groupList'
import { mapGetters } from 'vuex'

export default {
  name: 'buildgroup',
  watch: {
    search_user(val) {
      this.$refs.tree.filter(val)
    }
  },
  data() {
    return {
      isshow: false,
      search_user: '',
      userList: [
        {
          id: 1,
          label: '汽车学院',
          level: 1,
          children: [
            {
              id: 4,
              level: 2,
              label: '小冯老师',
              teacherNum: '2021001001',
              avatar: 'https://oss.metaxun.com/cloud/null/jpg/2024/05/16/1715860713627.jpg'
            },
            {
              id: 7,
              level: 2,
              label: '小陆老师',
              teacherNum: '2021001001',
              avatar: 'https://oss.metaxun.com/cloud/null/jpg/2024/05/16/1715860713627.jpg'
            }

          ]
        },
        {
          id: 2,
          level: 1,
          label: '人文学院',
          children: [
            {
              id: 5,
              level: 2,
              label: '小杜老师',
              teacherNum: '2021001001',
              avatar: 'https://oss.metaxun.com/cloud/null/jpg/2024/05/16/1715860713627.jpg'
            }
          ]
        },
        {
          id: 3,
          level: 1,
          label: '艺术学院',
          children: [
            {
              id: 6,
              level: 2,
              label: '李老师',
              teacherNum: '2021001001',
              avatar: 'https://oss.metaxun.com/cloud/null/jpg/2024/05/16/1715860713627.jpg'
            }
          ]
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'label',
        disabled: 'disabled'
      },
      // 所有员工数据
      allStaffData: [],
      //选中的原始数据
      selectedData: [],
      // 筛选后的数据
      filterSelectedData: [],
      type: 'build',
      groupName: [],
      groupId: ''
    }
  },
  computed: {
    ...mapGetters(['sidebarRouters', 'sidebar', 'avatar', 'name', 'account'])
  },
  methods: {
    show(type, id) {

      this.type = type
      if (type != 'build') {
        this.groupId = id
        this.getGroupUserTree()
      } else {
        this.getUserstoreTree()
      }
      this.isshow = true

    },
    removeDuplicatesById(array) {
      let uniqueArray = []
      let uniqueIds = new Set()
      array.forEach((obj) => {
        if (!uniqueIds.has(obj.userId)) {
          uniqueArray.push(obj)
          uniqueIds.add(obj.userId)
        }
      })
      return uniqueArray
    },
    filterNode(value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    // 选择
    getCheckedKeys(checkedNode) {
      if (checkedNode.children) {
        // 递归函数，用于获取某个节点的所有最子节点
        const AllLeafNodes = this.getAllLeafNodes(checkedNode)
        // 如果节点选中，则所有的子节点都进入selectData中
        if (this.isNodeChecked(checkedNode)) {
          // 使用 concat 方法保持顺序
          let objectArray = this.selectedData.concat(AllLeafNodes)
          // 遍历元素所有节点 勾选上节点相同的节点
          AllLeafNodes.map((item) => {
            this.selectSameNode(item, true)
          })
          // 通过id去重并保持顺序
          this.selectedData = this.removeDuplicatesById(objectArray)
        } else {
          // 原始数组
          let originalArray = this.selectedData
          // 要删除的数组
          let toRemoveArray = AllLeafNodes
          AllLeafNodes.map((item) => {
            this.selectSameNode(item, false)
          })
          // 根据 toRemoveArray 中的 id 属性值过滤掉 originalArray 中对应的对象
          this.selectedData = originalArray.filter(
            (obj) => !toRemoveArray.some((item) => item.userId === obj.userId)
          )
        }
      } else {
        // 如果节点选中，则子节点都进入selectData中
        if (this.isNodeChecked(checkedNode)) {
          // 相同的也要被勾选
          this.allStaffData.map((item) => {
            if (item.userId == checkedNode.userId && !item.disabled) {
              this.selectedData.push(item)
              this.$refs.tree.setChecked(item.id, true)
            }
          })
        }
        // 如果节点没有选中，则删除selectData中存在的元素
        else {
          this.selectSameNode(checkedNode, false)
          // 判断节点的id是否存在selectData中，存在则删除selectData中的该元素
          // 想同的也需要被删除
          if (this.selectedData.some((item) => item.userId === checkedNode.userId)) {
            this.selectedData = this.selectedData.filter(
              (item) => item.userId !== checkedNode.userId
            )
          }
        }
      }
      this.filterSelectedData = this.removeDuplicatesById(this.selectedData)
    },
    /* 递归函数，用于获取某个节点的所 有最子节点 */
    getAllLeafNodes(node, result = []) {
      if (node.children) {
        node.children.forEach((child) => {
          this.getAllLeafNodes(child, result)
        })
      } else {
        // 排除禁用节点
        if (!node.disabled) {
          result.push(node)
        }
      }
      return result
    },
    /* 判断节点点击是否被选中 */
    isNodeChecked(checkedNode) {
      return this.$refs.tree.getCheckedNodes().some((item) => {
        return item.id === checkedNode.id
      })
    },
    // 遍历树节点选择相同的节点
    selectSameNode(data, boolean) {
      this.allStaffData.map((item) => {
        if (item.userId == data.userId && !item.disabled) {
          this.$refs.tree.setChecked(item.id, boolean)
        }
      })
    },
    // 取消选择
    /* 删除用户 */
    delCheck(item) {
      this.selectSameNode(item, false)
      this.getCheckedKeys(item)
    },
    confirmBuild() {
      this.groupName = `${this.name}，` + this.filterSelectedData.map(e => e.label).join('，')
      if (this.type == 'build') {
        this.CreateGroup()
      } else {
        this.Groupinvite()
      }
    },
    concleBuild() {
      // 清空树状选择
      this.$refs.tree.setCheckedKeys([])
      this.selectedData = []
      this.filterSelectedData = []
      this.search_user = ''
      this.isshow = false
    },
    // 获取用户树
    async getUserstoreTree() {
      let res = await getuserTree()
      if (res.code == 200) {
        this.userList = this.handleTeachterData(res.data)
        this.allStaffData = []
        res.data.forEach(e => {
          if (e.userList && e.userList.length > 0) {
            e.userList.forEach(item => {
              this.allStaffData.push(item)
            })
          }
        })
      }
    },
    // 获取群组用户树
    async getGroupUserTree() {
      let res = await groupUserTree({ dataType: 1, groupId: this.groupId })
      if (res.code == 200) {
        this.userList = this.handleTeachterData(res.data)
        this.allStaffData = []
        res.data.forEach(e => {
          if (e.userList && e.userList.length > 0) {
            e.userList.forEach(item => {
              this.allStaffData.push(item)
            })
          }
        })
      }
    },
    // 处理教师数据，处理为树状结构
    handleTeachterData(data) {
      let arr = []
      if (data && data.length > 0) {
        data.forEach(e => {
          e.children = this.handleUserList(e.userList)
          e.level = 1
          e.id = e.branchId
          e.label = e.branchName
          if (e.children && e.children.length > 0) {
            arr.push(e)
          }
        })
      }
      return arr
    },
    handleUserList(arr) {
      let arr1 = []
      arr.forEach((e) => {
        if (e.userId != this.$store.getters.userId) {
          e.id = e.branchId + '_' + e.userId
          e.label = e.nickName + '（' + e.userName + '）'
          arr1.push(e)
        }
      })
      return arr1
    },
// 发送创建请求
    async CreateGroup() {
      let res = await createGroup({ userIds: this.filterSelectedData.map(e => e.userId), groupName: this.groupName })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '创建成功!'
        })
        this.concleBuild()
        this.$parent.getGroupList()
      }
    },
    // 发送邀请
    async Groupinvite() {
      let res = await inviteUser({ userIds: this.filterSelectedData.map(e => e.userId), groupId: this.groupId })
      if (res.code == 200) {
        this.$message({
          type: 'success',
          message: '邀请成功!'
        })
        this.concleBuild()
        this.$parent.getGroupList()
      }

    }
  }
}

</script>


<style scoped lang="scss">
::v-deep .el-tree-node__content {
  height: 50px;
}

.buildContent {
  display: flex;
  width: 100%;

  .content_l {
    width: 50%;
    border-right: 1px solid #dddddd;

    .search_bar {
      padding: 5px 10px;
      box-sizing: border-box;
    }

    .groupList {
      padding: 5px 10px;
      box-sizing: border-box;
      height: 480px;
      overflow-y: scroll;

      .custom_tree_node {
        display: flex;
        align-items: center;

        .user_avatar {
          width: 40px;
          height: 40px;
          border-radius: 50%;
          overflow: hidden;
          margin-right: 10px;

          img {
            width: 100%;
            height: 100%;
            border-radius: 50%;
          }
        }

        .user_info {
          margin-left: 10px;

          .user_name {
            font-size: 16px;
            font-weight: 600;
          }

          .user_num {
            font-size: 14px;
            color: #999;
          }
        }

        .branch_name {
          width: 290px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }

        .user_name {
          width: 220px;
          overflow: hidden;
          text-overflow: ellipsis;
          white-space: nowrap;
        }
      }
    }
  }

  .content_r {
    width: 50%;
    height: 100%;

    .checks_title {
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 12px;
      padding: 15px;
      box-sizing: border-box;
    }

    .checkUser {
      width: 100%;
      height: 480px;
      overflow: auto;
      //display: flex;
      //align-items: center;
      padding: 10px;
      box-sizing: border-box;
      //flex-wrap: wrap;

      .checkuserItem {
        width: 100%;
        //height: 40px;
        padding: 5px 10px;
        box-sizing: border-box;
        margin-bottom: 10px;
        display: flex;
        align-items: center;
        justify-content: space-between;
        border: 1px solid #ddd;

        .item_avatar {
          display: flex;
          align-items: center;

          img {
            width: 40px;
            height: 40px;
            border-radius: 50%;
            margin-right: 15px;

          }
        }

        .delCheck {
          font-size: 14px;
          color: red;
        }
      }
    }
  }

}


</style>
